package com.lkd.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lkd.dto.SkuClassDto;
import com.lkd.dto.SkuClassPageDto;
import com.lkd.entity.SkuClass;
import com.lkd.exception.BusinessException;
import com.lkd.mapper.SkuClassMapper;
import com.lkd.mapper.SkuMapper;
import com.lkd.result.PageBean;
import com.lkd.service.SkuClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SkuClassServiceImpl implements SkuClassService {

    @Autowired
    private SkuClassMapper skuClassMapper;
    @Autowired
    private SkuMapper skuMapper;
    //新建分类
    @Override
    public Boolean save(SkuClassDto skuClassDto) {
        if (StrUtil.isBlank(skuClassDto.getClassName())){
            throw new BusinessException("类别不能为空");
        }
        Boolean skuClass = skuClassMapper.save(skuClassDto);
        return skuClass;
    }

    //分页管理
    @Override
    public PageBean getByPage(SkuClassPageDto skuClassPageDto) {
        //开启分页
        PageHelper.startPage(skuClassPageDto.getPageIndex(), skuClassPageDto.getPageSize());
        //查询list
        List<SkuClass> list = skuClassMapper.getList(skuClassPageDto);
        Page<SkuClass> page = (Page<SkuClass>) list;
        return new PageBean(page.getPageNum(),
                page.getPageSize(),
                (long) page.getPages(),
                page.getTotal(),
                page.getResult());
    }
    //分页修改
    @Override
    public Boolean updateById(SkuClassDto skuClassDto) {
        if (skuClassDto.getClassId() == null){
            throw new BusinessException("修改ID不能为空");
        }
        Boolean skuClass = skuClassMapper.updateById(skuClassDto);
        return skuClass;
    }
    //分类回显
    @Override
    public SkuClassDto getById(String classId) {
        Integer clsId = Integer.parseInt(classId);
        SkuClassDto skuClassDto=skuClassMapper.getById(clsId);
        return skuClassDto;
    }

    //删除分类
    @Override
    public Boolean deleteById(String classId) {
        Integer clsId = Integer.valueOf(classId);
//        Boolean result = false;
        //查询当前商品分类下是否有商品
        Integer skuCount =skuMapper.getCountByClassId(clsId);
        if (skuCount>0){
            throw new BusinessException("当前分类下有商品，无法删除");
        }

        Boolean result = skuClassMapper.deleteById(clsId);

        return result;
    }
}
